﻿using Microsoft.Extensions.DependencyInjection;
using SBlogCore.Common.Helpers;

namespace SBlogCore.Common.DispatchProxyIn
{
    /// <summary>
    /// 通用代理
    /// </summary>
    [SkipScan]
    public static class DispatchProxyInExtensions
    {
        public static IServiceCollection AddDispatchProxyService<T, TProxy>(this IServiceCollection services)
            where T:IGlobalDispatchProxy
            where TProxy:GlobalDispatchProxy
        {
            //被代理的接口
            var type = typeof(T);
            //代理类
            var typeProxy = typeof(TProxy);
            //查找可以被转化为代理接口（继承了代理接口）的类，并且是接口，并且不是基接口
            var interfaceTypeList = ReflectionHelper.EffectiveTypes.Where(w=> type.IsAssignableFrom(w)&&w.IsInterface&&w!=type);
            //循环注入接口类与实现
            foreach (var interfaceType in interfaceTypeList)
            {
                services.AddSingleton(interfaceType, provider => {
                    dynamic invoke= typeof(DynamicProxy)
                    .GetMethod(nameof(DynamicProxy.Create))?
                    .MakeGenericMethod(interfaceType, typeProxy)//生成泛型方法(泛型类型，从左往右排序)
                    .Invoke(null,null)!;//参数一为调用实例，静态方法不考虑，参数二为方法的参数
                    if (invoke is GlobalDispatchProxy globalDispatch)
                    {
                        globalDispatch.Register(provider);
                    }
                    return invoke;
                });
            }
            return services;
        }
    }
}
